package com.adee.java.es;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;

import java.io.IOException;


public class ESTest {
    public static void main(String[] args) throws IOException {
        test();
    }

    public static void test() throws IOException {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("xt", "xt"));


        RestClientBuilder restClientBuilder = RestClient.builder(
                new HttpHost("8.142.104.99", 9200,"http"));

        // 认证和线程数
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            int threadCount = 10;
            httpClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build());

            return httpClientBuilder;
        });

        // 超时超时设置
        restClientBuilder.setRequestConfigCallback(requestConfigCallback -> {
            requestConfigCallback.setConnectTimeout(10);
            requestConfigCallback.setSocketTimeout(10);
            return requestConfigCallback;
        });

        // 创建客户端对象   虽然已经被弃用，但是了解基本使用还是没有问题  里面封装了RestClient
        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
        // 创建索引
        CreateIndexRequest user = new CreateIndexRequest("user");
        CreateIndexResponse response = client.indices().create(user, RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        System.out.println(acknowledged);

        System.out.println(client);

        // 关闭客户端连接
        client.close();
    }
}
